package com.cloudsigns.factorymanager2.engineering.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.cloudsigns.factorymanager2.R;
import com.cloudsigns.factorymanager2.cusenum.CommonEnum;
import com.cloudsigns.factorymanager2.engineering.IView.InAddPartrolOrderView;
import com.cloudsigns.factorymanager2.engineering.IView.InRegionListView;
import com.cloudsigns.factorymanager2.engineering.adapter.AddPublicationOrderAdapter;
import com.cloudsigns.factorymanager2.engineering.adapter.PopWindowAdapter;
import com.cloudsigns.factorymanager2.engineering.bean.MediaBean;
import com.cloudsigns.factorymanager2.engineering.bean.RegionBean;
import com.cloudsigns.factorymanager2.engineering.customview.SpinerPopWindow;
import com.cloudsigns.factorymanager2.engineering.presenter.AddPartrolOrderPresenter;
import com.cloudsigns.factorymanager2.engineering.presenter.RegionListPresenter;
import com.cloudsigns.factorymanager2.project.myinerface.ItemRemoveListener;
import com.cloudsigns.factorymanager2.project.utils.ConstantUtil;
import com.cloudsigns.factorymanager2.project.utils.DateUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by tony on 2018/5/5.
 */

public class AddPartrolOrderActivity extends Activity implements View.OnClickListener, AdapterView.OnItemClickListener, ItemRemoveListener, InAddPartrolOrderView, InRegionListView {
    private View rl_back;
    private TextView tv_title;
    private ImageView img_add_product;
    private View rl_add_product;
    //    private ListView lv;
    private TextView btn_save;
    private TextView edt_airport_name;
    private TextView edt_completion_date;
    private ImageView img_completion_date;
    private ScrollView scrollview;
    private LinearLayout ll_region;
    private LayoutInflater layoutInflater;
    //    private AddPublicationOrderAdapter adapter;
    private List<MediaBean> datas = new ArrayList<>();
    private String TAG = "AddPartrolOrderActivity";
    private AddPartrolOrderPresenter addPartrolOrderPresenter;
    private SpinerPopWindow<String> airportPopwindow;
    private PopWindowAdapter airportPopwindowAdapter;
    private List<String> airPopStrLs = new ArrayList<String>();
    List<RegionBean> airPopRegionBeanLs;
    RegionListPresenter mediaRegionListPresenter;
    private RegionBean selectedRegionBean;
    private List<String> selectedItemList = new ArrayList<String>();
    Map<String, List<MediaBean>> selectedBeanMap = new HashMap<>();
    private String beginDate, completeDate;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        // 沉浸式状态栏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    );
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN

                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        setContentView(R.layout.layout_add_partrol_order);

        addPartrolOrderPresenter = new AddPartrolOrderPresenter(this);
        mediaRegionListPresenter = new RegionListPresenter(this);
        layoutInflater = getLayoutInflater();
        init();
        mediaRegionListPresenter.getMediaRegionList();
    }

    ;

    private void init() {
        rl_back = findViewById(R.id.rl_back);
        tv_title = findViewById(R.id.tv_title);
        rl_add_product = findViewById(R.id.rl_add_product);
//        lv = findViewById(R.id.lv);
        btn_save = findViewById(R.id.btn_save);
        edt_airport_name = findViewById(R.id.edt_airport_name);
        edt_completion_date = findViewById(R.id.edt_completion_date);
        img_completion_date = findViewById(R.id.img_completion_date);
        scrollview = findViewById(R.id.scrollview);
        ll_region = findViewById(R.id.ll_region);

        tv_title.setText("巡查工单");
        rl_back.setOnClickListener(this);
        rl_add_product.setOnClickListener(this);
        btn_save.setOnClickListener(this);
        edt_airport_name.setOnClickListener(this);
        edt_completion_date.setOnClickListener(this);
        img_completion_date.setOnClickListener(this);

//        adapter = new AddPublicationOrderAdapter(this, TAG);
//        adapter.setData(datas);
//        adapter.setItemRemoveListener(this);
//        lv.setAdapter(adapter);

        airportPopwindow = new SpinerPopWindow<String>(this, this);
        airportPopwindowAdapter = new PopWindowAdapter(this, TAG);
        airportPopwindowAdapter.setData(airPopStrLs);
        airportPopwindow.setAdapter(airportPopwindowAdapter);
    }

    private void initData() {
        if (null != datas) {
            for (MediaBean mediaRegionBean : datas) {
                String areaName = mediaRegionBean.getAreaName();

                if (selectedBeanMap.containsKey(areaName)) {
                    selectedBeanMap.get(areaName).add(mediaRegionBean);
                } else {
                    List<MediaBean> beanList = new ArrayList<>();
                    beanList.add(mediaRegionBean);
                    selectedBeanMap.put(areaName, beanList);

                }
            }
        }

        updateUi();
    }


    private void updateUi() {


        if (null != selectedBeanMap && null != ll_region) {
            ll_region.removeAllViews();

            for (Map.Entry<String, List<MediaBean>> entry : selectedBeanMap.entrySet()) {
                View view = layoutInflater.inflate(R.layout.layout_point_location_content, null);
                TextView tv_area_name = view.findViewById(R.id.tv_area_name);
                tv_area_name.setText(entry.getKey());

                ListView lv_media = view.findViewById(R.id.lv_media);

                List<MediaBean> mediaRegionBeanList = entry.getValue();
                AddPublicationOrderAdapter adapter = new AddPublicationOrderAdapter(this, TAG);
//                PointLocationAdapter adapter = new PointLocationAdapter(this, TAG);
                adapter.setData(mediaRegionBeanList);
                adapter.setItemRemoveListener(this);
                lv_media.setAdapter(adapter);
                view.setTag(mediaRegionBeanList);


                ll_region.addView(view);


            }
        }

        scrollview.smoothScrollTo(0, 0);

    }


    private void initAirportPopData() {
        if (null != airPopRegionBeanLs) {
            airPopStrLs.clear();
            for (RegionBean regionBean : airPopRegionBeanLs) {
                airPopStrLs.add(regionBean.getRegionName());
            }
            airportPopwindowAdapter.setData(airPopStrLs);
            airportPopwindowAdapter.notifyDataSetChanged();
        }
    }


    private void showAirportPop() {
        airportPopwindow.setWidth(edt_airport_name.getWidth());
        airportPopwindow.showAsDropDown(edt_airport_name);
    }

    private void save() {
        if (null != addPartrolOrderPresenter)
            addPartrolOrderPresenter.addPartrolOrder();
    }


    @Override
    public void remove(int positon) {

    }

    @Override
    public void remove(View view) {
        MediaBean bean = (MediaBean) view.getTag();
        String areaName = bean.getAreaName();
        if (selectedBeanMap.containsKey(areaName)) {
            selectedBeanMap.get(areaName).remove(bean);
            if (selectedBeanMap.get(areaName).size() == 0)
                selectedBeanMap.remove(areaName);

            selectedItemList.remove(bean.getId());
            datas.remove(bean);
            updateUi();
        }

    }

    @Override
    public void onClick(View view) {
        TextView tv;
        Intent mIntent;
        switch (view.getId()) {
            case R.id.rl_back:
                finish();
                break;
            case R.id.rl_add_product:
                if (null != selectedRegionBean) {
                    mIntent = new Intent(AddPartrolOrderActivity.this, SelectMeidaForSuperActivity.class);
                    mIntent.putExtra(ConstantUtil.KEY_1, (Serializable) selectedItemList);
                    mIntent.putExtra(ConstantUtil.KEY_2, selectedRegionBean);
                    mIntent.putExtra("EngineeringORderCategory", CommonEnum.EngineeringORderCategory.PATROL);
                    startActivityForResult(mIntent, ConstantUtil.START_ACTIVITY_KEY_1);
                }


                break;
            case R.id.edt_airport_name:

                showAirportPop();
                break;

            case R.id.edt_completion_date:
                mIntent = new Intent(AddPartrolOrderActivity.this, TwoDatePickActivity.class);
                mIntent.putExtra(ConstantUtil.KEY_1, TAG);
                startActivityForResult(mIntent, ConstantUtil.START_ACTIVITY_KEY_2);

                break;
            case R.id.img_completion_date:
                mIntent = new Intent(AddPartrolOrderActivity.this, TwoDatePickActivity.class);
                mIntent.putExtra(ConstantUtil.KEY_1, TAG);
                startActivityForResult(mIntent, ConstantUtil.START_ACTIVITY_KEY_2);
                break;

            case R.id.btn_save:
                save();
                break;
        }
    }


    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        edt_airport_name.setText(airPopStrLs.get(i));
        selectedRegionBean = airPopRegionBeanLs.get(i);

        if (null != airportPopwindow)
            airportPopwindow.dismiss();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case ConstantUtil.START_ACTIVITY_KEY_1:
                if (data != null) {
                    if (data != null) {
                        selectedItemList = (List<String>) data.getSerializableExtra(ConstantUtil.KEY_1);
                        datas = (List<MediaBean>) data.getSerializableExtra(ConstantUtil.KEY_2);
                        initData();
                    }
                }
                break;
            case ConstantUtil.START_ACTIVITY_KEY_2:
                if (data != null) {
                    beginDate = data.getStringExtra(ConstantUtil.KEY_1);
                    completeDate = data.getStringExtra(ConstantUtil.KEY_2);
                    edt_completion_date.setText(beginDate + "-" + completeDate);
                }
                break;


        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public long getBeginDate() {
        if (!TextUtils.isEmpty(beginDate))
            return DateUtil.getMillis(beginDate);

        return 0;
    }

    @Override
    public long getCompleteDate() {
        if (!TextUtils.isEmpty(completeDate))
            return DateUtil.getMillis(completeDate);

        return 0;
    }

    @Override
    public List<MediaBean> getMediaList() {
        return datas;
    }

    @Override
    public String getRegionId() {
        if (null != selectedRegionBean)
            return selectedRegionBean.getId();
        return "";
    }

    @Override
    public String getRegionName() {
        if (null != selectedRegionBean)
            return selectedRegionBean.getRegionName();

        return "";
    }

    @Override
    public void addPartrolOrderSuccessed(String id) {
        Toast.makeText(this, "保存成功" + id, Toast.LENGTH_SHORT).show();
        Intent mIntent = new Intent();
        mIntent.putExtra(ConstantUtil.KEY_1, true);
        setResult(ConstantUtil.CREATED_ORDER, mIntent);
        finish();
    }

    @Override
    public void getMediaRegionListSuccessed(List<RegionBean> regionBeanList) {
        airPopRegionBeanLs = regionBeanList;
        initAirportPopData();
    }

    @Override
    public void showFailedError(String desc) {
        Toast.makeText(this, desc, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

}
